package dao;

import hibernate.HibernateUtil;
import negocio.Remito;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import dto.RemitoDTO;
import entities.EnvioEntity;
import entities.ItemRemitoEntity;
import entities.RemitoEntity;

public class RemitoDAO {
	private static RemitoDAO instancia = null;
	private static SessionFactory sf = null;
	
	private RemitoDAO(){}
	
	public static RemitoDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new RemitoDAO();
		} 
		return instancia;
	}
	
	/*public dto.RemitoDTO ObtenerRemito(dto.RemitoDTO remito)
	{
		SessionFactory sf =  HibernateUtil.getSessionFactory();
		Session session = sf.getCurrentSession();
		org.hibernate.Transaction t =  session.beginTransaction();
		entities.RemitoEntity nuevoRemito = (RemitoEntity) session.createQuery("select r from RemitoEntity r where r.id =:numero").setParameter("numero", remito.getId()).uniqueResult();
		//conversion falta
		
		session.close(); 
		return null;
	}*/
	
	public void grabarRemito(RemitoEntity remito){
		Session session = sf.openSession();
		session.beginTransaction();
		session.persist(remito);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}
	
	public void actualizarRemito(RemitoEntity remito){
		Session session = sf.openSession();
		session.beginTransaction();
		session.saveOrUpdate(remito);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}
	
	public RemitoEntity LoadRemito(int id) 
	{
		Session session = sf.openSession();
		session.beginTransaction();
		RemitoEntity rem = (RemitoEntity) session.get(RemitoEntity.class, id);
		session.flush();
		session.getTransaction().commit();
		session.close();
		return rem;
	}

	public boolean pagarFactura(RemitoDTO remito) 
	{
		try
		{
			Remito r = new Remito(remito);
			RemitoEntity rEnt = r.toEntity();
			rEnt.setTipo("factura");
			RemitoDAO.getInstancia().grabarRemito(rEnt);
			float valor =0;
			for (ItemRemitoEntity it : rEnt.getItemRemito()) 
			{
				valor=valor+it.getImporte();
			}
			CuentaCorrienteDAO.getInstancia().actualizarCuentaCorrienteCliente(rEnt.getCliente().getId(), valor);
			return true;
		}
		catch(Exception e)
		{
			return false;
		}
	}
}

